import React, { useState, useEffect } from 'react';
import { Card, Form, Input, Button, Slider, Tabs, Table, Select, Space, Tag, Switch, InputNumber, Alert } from 'antd';
import { SearchOutlined, SettingOutlined, LineChartOutlined, LoadingOutlined } from '@ant-design/icons';
import { useRetrievalContext } from '../../contexts/RetrievalContext';
import { useApiSettings } from '../../contexts/ApiSettingsContext';
import RetrievalVisualizer from './RetrievalVisualizer';

const { TabPane } = Tabs;
const { Option } = Select;

const RetrievalSandbox: React.FC = () => {
  const { 
    performSearch, 
    searchResults, 
    loading, 
    searchParams,
    updateSearchParams,
    previousResults
  } = useRetrievalContext();
  const { apiSettings } = useApiSettings();
  const [query, setQuery] = useState('');
  const [activeTab, setActiveTab] = useState('params');
  const [apiConnectionStatus, setApiConnectionStatus] = useState<'checking' | 'success' | 'error' | 'idle'>('idle');

  // 检查API连接配置
  useEffect(() => {
    const checkApiSettings = async () => {
      setApiConnectionStatus('checking');
      if (!apiSettings.embedding.apiKey || !apiSettings.retrieval.apiKey) {
        setApiConnectionStatus('error');
        return;
      }
      
      // 这里可以添加实际的API连接检查逻辑
      // 为了演示，我们只是模拟延迟
      await new Promise(resolve => setTimeout(resolve, 800));
      setApiConnectionStatus('success');
    };
    
    checkApiSettings();
  }, [apiSettings]);

  const handleSearch = () => {
    if (query.trim()) {
      performSearch(query);
      // 自动切换到可视化标签
      if (activeTab === 'params') {
        setActiveTab('visualization');
      }
    }
  };

  // 列定义
  const columns = [
    {
      title: '排名',
      dataIndex: 'rank',
      key: 'rank',
      width: 80,
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      ellipsis: true,
    },
    {
      title: '相关度',
      dataIndex: 'score',
      key: 'score',
      render: (score: number) => (
        <Tag color={score > 0.8 ? 'green' : score > 0.5 ? 'blue' : 'orange'}>
          {(score * 100).toFixed(2)}%
        </Tag>
      ),
      width: 100,
      sorter: (a: any, b: any) => a.score - b.score,
    },
    {
      title: '类型',
      dataIndex: 'metadata',
      key: 'resultType',
      render: (metadata: any) => (
        <Tag color={
          metadata.resultType === 'hybrid' ? 'purple' : 
          metadata.resultType === 'vector' ? 'blue' : 
          'orange'
        }>
          {metadata.resultType === 'hybrid' ? '混合' : 
           metadata.resultType === 'vector' ? '向量' : '关键词'}
        </Tag>
      ),
      width: 80,
    },
    {
      title: '来源',
      dataIndex: 'source',
      key: 'source',
      width: 150,
      ellipsis: true,
      render: (source: string) => (
        <a href={source} target="_blank" rel="noopener noreferrer">
          {new URL(source).hostname}
        </a>
      ),
    },
  ];

  return (
    <Card title="检索策略沙盒" className="retrieval-sandbox">
      {apiConnectionStatus === 'error' && (
        <Alert
          message="API配置不完整" 
          description="请先在API连接器中配置Embedding服务和检索服务" 
          type="warning"
          showIcon
          style={{ marginBottom: 16 }}
        />
      )}
      
      <div className="search-section">
        <Input.Search
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="输入测试查询..."
          enterButton={<Button type="primary" icon={<SearchOutlined />}>检索</Button>}
          onSearch={handleSearch}
          loading={loading}
          size="large"
          disabled={apiConnectionStatus === 'error'}
        />
      </div>
      
      <Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab}
        className="sandbox-tabs"
      >
        <TabPane 
          tab={<span><SettingOutlined />检索参数</span>} 
          key="params"
        >
          <Form layout="vertical">
            <Form.Item label="向量搜索阈值">
              <Slider
                min={0}
                max={1}
                step={0.01}
                value={searchParams.similarityThreshold}
                onChange={(value) => updateSearchParams('similarityThreshold', value)}
                marks={{
                  0: '0',
                  0.5: '0.5',
                  1: '1'
                }}
                tooltip={{ 
                  formatter: (value) => (value !== undefined ? `${(value * 100).toFixed(0)}%` : '0%') 
                }}
              />
            </Form.Item>
            
            <Form.Item label="结果数量">
              <InputNumber
                min={1}
                max={50}
                value={searchParams.topK}
                onChange={(value) => updateSearchParams('topK', value || 10)}
              />
            </Form.Item>
            
            <Form.Item label="混合搜索">
              <Switch
                checked={searchParams.hybridSearch}
                onChange={(checked) => updateSearchParams('hybridSearch', checked)}
              />
              <span style={{ marginLeft: 8 }}>
                {searchParams.hybridSearch ? '向量 + 关键词' : '仅向量'}
              </span>
            </Form.Item>
            
            {searchParams.hybridSearch && (
              <>
                <Form.Item label="关键词权重">
                  <Slider
                    min={0}
                    max={1}
                    step={0.05}
                    value={searchParams.keywordWeight}
                    onChange={(value) => updateSearchParams('keywordWeight', value)}
                    marks={{
                      0: '向量',
                      0.5: '均衡',
                      1: '关键词'
                    }}
                    tooltip={{ 
                      formatter: (value) => (value !== undefined ? `${(value * 100).toFixed(0)}%` : '0%') 
                    }}
                  />
                </Form.Item>
                
                <Form.Item label="重排序方法">
                  <Select
                    value={searchParams.reranking}
                    onChange={(value) => updateSearchParams('reranking', value)}
                  >
                    <Option value="none">无重排序</Option>
                    <Option value="reciprocal">倒数排名融合</Option>
                    <Option value="weighted">加权分数融合</Option>
                    <Option value="custom">自定义规则</Option>
                  </Select>
                </Form.Item>
              </>
            )}
            
            <Form.Item>
              <Space>
                <Button 
                  type="primary" 
                  onClick={handleSearch} 
                  loading={loading}
                  disabled={apiConnectionStatus === 'error' || !query.trim()}
                >
                  应用参数并检索
                </Button>
                <Button 
                  onClick={() => performSearch(query, true)}
                  disabled={apiConnectionStatus === 'error' || !query.trim() || searchResults.length === 0}
                >
                  比较结果差异
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </TabPane>
        
        <TabPane 
          tab={<span><LineChartOutlined />结果可视化</span>} 
          key="visualization"
        >
          <RetrievalVisualizer 
            searchResults={searchResults} 
            query={query}
            previousResults={previousResults}
          />
        </TabPane>
      </Tabs>
      
      <div className="results-table">
        <Table
          dataSource={searchResults.map((result, index) => ({
            ...result,
            rank: index + 1,
            key: index,
          }))}
          columns={columns}
          loading={loading}
          pagination={{ pageSize: 5 }}
          size="small"
          expandable={{
            expandedRowRender: record => (
              <div style={{ padding: '0 20px' }}>
                <p>{record.content}</p>
                <div style={{ marginTop: 8 }}>
                  {Object.entries(record.metadata)
                    .filter(([key]) => !['resultType', 'hybridBoost'].includes(key))
                    .map(([key, value]) => (
                      <Tag key={key} style={{ marginBottom: 4 }}>
                        {key}: {typeof value === 'object' ? JSON.stringify(value) : value}
                      </Tag>
                    ))}
                </div>
              </div>
            ),
            rowExpandable: record => Boolean(record.content),
          }}
        />
      </div>
    </Card>
  );
};

export default RetrievalSandbox; 